package org.jeecg.modules.scm.service.impl;

import cfca.trustsign.common.vo.cs.SignContractVO;
import cfca.trustsign.common.vo.cs.SignInfoVO;
import cfca.trustsign.demo.op.CfcaOp;
import cfca.trustsign.demo.util.TimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.scm.constant.ScmConstant;
import org.jeecg.modules.scm.entity.*;
import org.jeecg.modules.scm.mapper.*;
import org.jeecg.modules.scm.service.IScmReceivablesTransferContractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: scm_receivables_transfer_contract
 * @Author: jeecg-boot
 * @Date: 2021-11-09
 * @Version: V1.0
 */
@Service
public class ScmReceivablesTransferContractServiceImpl extends ServiceImpl<ScmReceivablesTransferContractMapper, ScmReceivablesTransferContract> implements IScmReceivablesTransferContractService {
    @Resource
    private ScmCloudChainTransferContractMapper scmCloudChainTransferContractMapper;
    @Resource
    private ScmReceivablesTransferContractMapper scmReceivablesTransferContractMapper;
    @Resource
    private ScmReceivablesTransferApplicationMapper scmReceivablesTransferApplicationMapper;
    @Resource
    private ScmCloudChainMapper scmCloudChainMapper;
    @Resource
    private ScmCusInfoMapper scmCusInfoMapper;
    @Resource
    private ISysBaseAPI sysBaseAPI;

    @Override
    public List<ScmCloudChain> findCloudChain(String id) {
        LambdaQueryWrapper<ScmCloudChainTransferContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ScmCloudChainTransferContract::getTransferContractId, id);
        List<ScmCloudChainTransferContract> list = scmCloudChainTransferContractMapper.selectList(queryWrapper);
        List<ScmCloudChain> scmCloudChainList = new ArrayList<>();
        for (ScmCloudChainTransferContract s : list) {
            ScmCloudChain scmCloudChain = scmCloudChainMapper.selectById(s.getChainNo());
            scmCloudChainList.add(scmCloudChain);
        }
        return scmCloudChainList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> sign(String contractId, Integer cusNo) {
        Result<String> result = new Result<>();

        ScmCusInfo scmCusInfo = scmCusInfoMapper.selectById(cusNo);
        ScmReceivablesTransferContract contract = scmReceivablesTransferContractMapper.selectById(contractId);
        //获取合同转让人id
        Integer transferorCusNo = contract.getTransferorCusNo();
        //获取合同受让人id
        Integer transfereeCusNo = contract.getTransfereeCusNo();
        if (!cusNo.equals(transferorCusNo) && !cusNo.equals(transfereeCusNo)) {
            return Result.error("用户所属客户不属于转让人和受让人");
        }
        if (cusNo.equals(transferorCusNo) && oConvertUtils.isNotEmpty(contract.getTransferorContractTime())) {
            return Result.error("转让人已签约，请勿重复签约！");
        }
        if (cusNo.equals(transfereeCusNo) && oConvertUtils.isNotEmpty(contract.getTransfereeContractTime())) {
            return Result.error("受让人已签约，请勿重复签约！");
        }
        JSONObject cusResult = JSONObject.parseObject(CfcaOp.getCus(scmCusInfo.getCusName(), scmCusInfo.getCertificateType(), scmCusInfo.getCertificateNo()));
        String cfcaUserId = cusResult.getJSONObject("userInfo").getString("userId");
        //转让人签约
        if (cusNo.equals(transferorCusNo)) {
            //调用CFCA签约合同接口
            SignContractVO signContract = new SignContractVO();
            signContract.setContractNo(contract.getCfcaContractNo());
            SignInfoVO signInfo = new SignInfoVO();
            signInfo.setUserId(cfcaUserId);
            signInfo.setLocation("211.94.108.226");
            signInfo.setProjectCode("003");
            signInfo.setSignLocation("transferor_sign");
            signInfo.setAuthorizationTime(TimeUtil.getCurrentTime(TimeUtil.FORMAT_14));
            signContract.setSignInfo(signInfo);
            JSONObject signResult = JSONObject.parseObject(CfcaOp.signContract(signContract));
            if (oConvertUtils.isNotEmpty(signResult.getString("errorMessage"))){
                return Result.error(signResult.getString("errorMessage"));
            }

            ScmReceivablesTransferContract s = new ScmReceivablesTransferContract();
            s.setId(contract.getId());
            //更新转让人签约时间
            s.setTransferorContractTime(new Date());
            scmReceivablesTransferContractMapper.updateById(s);
            result.setCode(CommonConstant.SC_OK_200);
            result.setSuccess(true);
            result.setMessage("转让人签约成功！");
        }
        //受让人签约
        if (cusNo.equals(transfereeCusNo)) {
            //调用CFCA签约合同接口
            SignContractVO signContract = new SignContractVO();
            signContract.setContractNo(contract.getCfcaContractNo());
            SignInfoVO signInfo = new SignInfoVO();
            signInfo.setUserId(cfcaUserId);
            signInfo.setLocation("211.94.108.226");
            signInfo.setProjectCode("003");
            signInfo.setSignLocation("transferee_sign");
            signInfo.setAuthorizationTime(TimeUtil.getCurrentTime(TimeUtil.FORMAT_14));
            signContract.setSignInfo(signInfo);
            JSONObject signResult = JSONObject.parseObject(CfcaOp.signContract(signContract));
            if (oConvertUtils.isNotEmpty(signResult.getString("errorMessage"))){
                return Result.error(signResult.getString("errorMessage"));
            }

            ScmReceivablesTransferContract s = new ScmReceivablesTransferContract();
            s.setId(contract.getId());
            //更新受让人签约时间
            s.setTransfereeContractTime(new Date());
            scmReceivablesTransferContractMapper.updateById(s);
            result.setCode(CommonConstant.SC_OK_200);
            result.setSuccess(true);
            result.setMessage("受让人签约成功！");
        }
        ScmReceivablesTransferContract newContract = scmReceivablesTransferContractMapper.selectById(contractId);
        if (oConvertUtils.isNotEmpty(newContract.getTransferorContractTime()) && oConvertUtils.isNotEmpty(newContract.getTransfereeContractTime())) {
            //更新转让状态为已完结
            ScmReceivablesTransferApplication application = scmReceivablesTransferApplicationMapper.selectById(contract.getTransferApplyId());
            application.setStatus(ScmConstant.RECEIVABLES_TRANSFER_STATUS_FINISH);
            scmReceivablesTransferApplicationMapper.updateById(application);

            ScmReceivablesTransferContract s = new ScmReceivablesTransferContract();
            s.setId(contract.getId());
            //更新合同状态为已签约
            s.setStatus(ScmConstant.RECEIVABLES_CONTRACT_STATUS_SIGNED);
            //设置生效时间
            s.setEffectiveTime(new Date());
            scmReceivablesTransferContractMapper.updateById(s);

            List<ScmCloudChain> chainList = findCloudChain(contractId);
            for (ScmCloudChain chain : chainList) {
                //设置合同关联云链单持有人为转让的受让人
                chain.setOwnerCusNo(newContract.getTransfereeCusNo());
                //设置合同关联云链单状态为已转让
                chain.setStauts(ScmConstant.CHAIN_STATUS_TRANSFERRED);
                scmCloudChainMapper.updateById(chain);
            }

            result.setMessage(result.getMessage() + " 合同签约成功");
        }
        return result;
    }

}
